package com.lsh.oms.core.service.order;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lsh.base.common.json.JsonUtils;
import com.lsh.oms.api.model.order.delivery.OrderSendHeadDTO;
import com.lsh.oms.api.model.other.OrderShippingHeadDto;
import com.lsh.oms.api.model.other.OrderShippingHeadKaDto;
import com.lsh.oms.core.constant.ReturnCode;
import com.lsh.oms.core.enums.*;
import com.lsh.oms.core.exception.BusinessException;
import com.lsh.oms.core.model.calService.CalResultVo;
import com.lsh.oms.core.model.calService.CalShippingHeadVo;
import com.lsh.oms.core.model.order.*;
import com.lsh.oms.core.model.payment.BillPaymentInfo;
import com.lsh.oms.core.utils.DateUtil;
import com.lsh.oms.core.utils.IdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Project Name: lsh-oms
 *
 * @author peter
 * @date 17/3/27
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
@Slf4j
public class OrderFactory {

    /**
     * pms 发货单处理
     *
     * @param sendDto
     * @param orderHead
     * @param calVo
     * @return
     */
    public static OrderShippingHeadWithBLOBs createShippingHead(OrderSendHeadDTO sendDto, OrderHead orderHead, CalResultVo calVo) {

        OrderShippingHeadWithBLOBs osh = new OrderShippingHeadWithBLOBs();
        osh.setShippingOrderId(IdGenerator.genId());
        // 来自订单的属性
        osh.setOrderId(orderHead.getOrderCode());
        osh.setAddressId(orderHead.getAddressCode());
        osh.setAddressInfo(orderHead.getAddressInfo());
        osh.setProvince(orderHead.getProvince() + "");
        osh.setCity(orderHead.getCity() + "");
        osh.setCounty(orderHead.getDistrict() + "");
        osh.setArea(orderHead.getArea() + "");
        osh.setOrderedAt(orderHead.getOrderTime());
        osh.setUid(orderHead.getUserCode());
        osh.setStorageTypeId(orderHead.getStorageType());
        osh.setZoneId(orderHead.getRegionCode());
        osh.setOrderedAt(orderHead.getOrderTime());
        osh.setVenderId(orderHead.getVenderId());
        osh.setTmsOrderId(orderHead.getOrderCode());
        osh.setFOrderId(orderHead.getParentOrderCode());

        //来自计算服务
        CalShippingHeadVo vo = calVo.getHead();
        osh.setSkuCount(new BigDecimal(vo.getSku_count()));
        osh.setRealSkuCount(vo.getReal_sku_count());

        BigDecimal money = new BigDecimal(vo.getMoney());
        osh.setMoney(money.compareTo(BigDecimal.ZERO) == 0 ? new BigDecimal("0.01") : money);
        osh.setFloorMoney(new BigDecimal(vo.getFloor_money()));
        osh.setCouponMoney(new BigDecimal(vo.getCoupon_money()));
        log.info(orderHead.getOrderCode() + "ship vo ext is -" + vo.getExt().length() + ":" + vo.getExt());
        osh.setExt(vo.getExt());
        //来自ofc
        osh.setTurnoverboxNum(sendDto.getTurnoverbox_num().intValue());
        osh.setBoxNum(sendDto.getBox_num().intValue());
        osh.setCarType(sendDto.getCar_type());
        osh.setWaybillId(sendDto.getWaybill_id());
        osh.setWarehouseId(sendDto.getWarehouse_id());
        osh.setWarehouseName(sendDto.getWarehouse_name());
        osh.setProviderId(sendDto.getProvider_id());
        osh.setOrderFrom(OrderFrom.ZY.getValue());
        Integer sale_model = sendDto.getSale_model();
        Integer delivery_type = sendDto.getDelivery_type();

        osh.setStatus(ShippingStatus.WAIT_DELIVER.getIndex());
        if (delivery_type == 3) {
            osh.setOrderFrom(OrderFrom.YC.getValue());
        }
        if (delivery_type == 4) {
            osh.setStatus(ShippingStatus.DELIVERING.getIndex());
        }

        // 初始默认值
        osh.setDelayType(DelayType.NO_DELAY.getIndex());
        osh.setReceiptStatus(ShippingReceiptStatus.UN_RECEIPT.getIndex());
        osh.setIsValid(Valid.ENABLE.getValue());
        osh.setIsPrecedence(1);
        osh.setTmsId(0L);
        osh.setAfsFlag(0); // 不再使用 不再绑定第二单
        int time = (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
        osh.setCreatedAt(time);
        osh.setUpdatedAt(time);
        osh.setShippedAt(time);
        osh.setActivedAt(time);

        int userType = getUserType(orderHead);
        // TODO 2019-12-24 peter
        osh.setOmsExt(omsExtBuilder(sendDto, orderHead, userType).toJSONString());
        // TODO 2019-12-24 peter
        osh.setWarehouseData(dataBuilder(sendDto, orderHead).toJSONString());

        // 以下值 通知
        osh.setTransUid(0L);
        osh.setWaybillNo("");
        osh.setRouteId(0L);
        osh.setSeq(1);

        return osh;
    }

    private static JSONObject omsExtBuilder(OrderSendHeadDTO headDto, OrderHead orderHead, int userType) {
        JSONObject omsExtJson = new JSONObject();
        String pickerInfo = headDto.getObd_order_picking_info();
        if (StringUtils.isNotBlank(pickerInfo)) {
            JSONObject pickingInfo = JSON.parseObject(pickerInfo);
            omsExtJson.put("pickingInfo", pickingInfo);
        } else {
            omsExtJson.put("pickingInfo", "{}");
        }

        omsExtJson.put("supplierGroupId", orderHead.getSupplierGroupId());
        omsExtJson.put("userType", userType);
        OrderHeadExt headExt = orderHead.getExtObject();
        JSONObject jsonObject = JSON.parseObject(headExt.getExt());
        omsExtJson.put("saleInfo", jsonObject.getJSONObject("saleInfo"));

        return omsExtJson;
    }

    private static JSONObject dataBuilder(OrderSendHeadDTO headDto, OrderHead orderHead) {
        JSONObject dataJson = new JSONObject();

        dataJson.put("type", headDto.getType());
        dataJson.put("system", headDto.getSystem());
        dataJson.put("waybill_id", headDto.getWaybill_id());
        dataJson.put("collect_code", headDto.getCollect_code());
        dataJson.put("pick_time", headDto.getPick_time());
        dataJson.put("delivery_time", headDto.getDelivery_time());
        dataJson.put("so_user_id", headDto.getSo_user_id());
        dataJson.put("out_order_id", headDto.getOut_order_id());
        dataJson.put("provider_id", headDto.getProvider_id());
        dataJson.put("order_dc", headDto.getOrder_dc());
        dataJson.put("delivery_type", headDto.getDelivery_type());
        dataJson.put("sale_model", headDto.getSale_model());
        dataJson.put("obd_ext", headDto.getObd_ext());
        dataJson.put("pay_type", orderHead.getPayType());

        return dataJson;
    }

    /**
     * 冻品发货处理
     *
     * @param headDto
     * @param oh
     * @param calVo
     * @return
     */
    public static OrderShippingHeadWithBLOBs createShippingHead(OrderShippingHeadDto headDto, OrderHead oh, CalResultVo calVo) {

        OrderShippingHeadWithBLOBs osh = new OrderShippingHeadWithBLOBs();

        osh.setOrderId(oh.getOrderCode());
        osh.setAddressId(oh.getAddressCode());
        osh.setAddressInfo(oh.getAddressInfo());
        osh.setProvince(oh.getProvince() + "");
        osh.setCity(oh.getCity() + "");
        osh.setCounty(oh.getDistrict() + "");
        osh.setArea(oh.getArea() + "");
        osh.setTmsOrderId(IdGenerator.genId());
        osh.setSeq(1);
        osh.setOrderedAt(oh.getOrderTime());
        osh.setUid(oh.getUserCode());
        Map<String, Object> map = new HashMap<>();
        map.put("otherShippingId", headDto.getShippingOrderId());
        osh.setOmsExt(JsonUtils.obj2Json(map));
        osh.setWarehouseId(StringUtils.isAnyEmpty(headDto.getWarehouseId()) ? "" : headDto.getWarehouseId());
        osh.setWarehouseName(StringUtils.isAnyEmpty(headDto.getWarehouseName()) ? "" : headDto.getWarehouseName());
        int time = (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
        osh.setCreatedAt(time);
        osh.setUpdatedAt(time);
        osh.setArrivedAt(time);
        CalShippingHeadVo vo = calVo.getHead();
        osh.setSkuCount(new BigDecimal(vo.getSku_count()));
        osh.setRealSkuCount(vo.getReal_sku_count());
        osh.setMoney(new BigDecimal(vo.getMoney()));

        if (StringUtils.isBlank(vo.getFloor_money())) {
            osh.setFloorMoney(BigDecimal.ZERO);
        } else {
            osh.setFloorMoney(new BigDecimal(vo.getFloor_money()));
        }

        if (StringUtils.isBlank(vo.getCoupon_money())) {
            osh.setCouponMoney(BigDecimal.ZERO);
        } else {
            osh.setCouponMoney(new BigDecimal(vo.getCoupon_money()));
        }

        osh.setActivedAt(vo.getActived_at());
        osh.setShippedAt(vo.getShipped_at());
        osh.setTmsId(0L);
        osh.setTransUid(0L);
        osh.setWaybillNo("");
        //初始化0，无业务使用，仅供mis显示用
        osh.setReceiptStatus(0);
        osh.setDelayType(0);
        osh.setZoneId(Integer.parseInt(vo.getZone_id()));

        osh.setWarehouseId("oms");
        osh.setWarehouseName("oms");

        osh.setStorageTypeId(oh.getStorageType());
        osh.setOrderFrom(1);
        osh.setCarType("");
        osh.setTurnoverboxNum(0);
        osh.setBoxNum(0);
        osh.setIsPrecedence(1);
        osh.setIsValid(1);
        osh.setWarehouseData("");

        //TODO:head_info
        CalShippingHeadVo head = calVo.getHead();
        String ext = head.getExt();
        com.alibaba.fastjson.JSONObject extObject = com.alibaba.fastjson.JSONObject.parseObject(ext);
        osh.setExt(extObject.toJSONString());
        osh.setStatus(1);

        osh.setShippingOrderId(IdGenerator.genId());
        return osh;
    }

    /**
     * KA发货处理
     *
     * @param shippingKAHeadDto
     * @param oh
     * @param calVo
     * @return
     */
    public static OrderShippingHeadWithBLOBs createShippingHead(OrderShippingHeadKaDto shippingKAHeadDto, OrderHead oh, CalResultVo calVo) {

        OrderShippingHeadWithBLOBs osh = new OrderShippingHeadWithBLOBs();

        //TODO 2019-09-08 venderId
        osh.setVenderId(oh.getVenderId());

        osh.setOrderId(oh.getOrderCode());
        osh.setAddressId(oh.getAddressCode());
        osh.setAddressInfo(oh.getAddressInfo());
        osh.setProvince(oh.getProvince() + "");
        osh.setCity(oh.getCity() + "");
        osh.setCounty(oh.getDistrict() + "");
        osh.setArea(oh.getArea() + "");
        osh.setStorageTypeId(oh.getStorageType());
        osh.setOrderedAt(oh.getOrderTime());
        osh.setUid(oh.getUserCode());

        CalShippingHeadVo vo = calVo.getHead();
        osh.setSkuCount(new BigDecimal(vo.getSku_count()));
        osh.setRealSkuCount(vo.getReal_sku_count());
        osh.setMoney(new BigDecimal(vo.getMoney()));
        osh.setFloorMoney(new BigDecimal(vo.getFloor_money()));
        osh.setCouponMoney(new BigDecimal(vo.getCoupon_money()));
        osh.setActivedAt(vo.getActived_at());
        osh.setShippedAt(vo.getShipped_at());
        osh.setZoneId(Integer.parseInt(vo.getZone_id()));

        Map<String, Object> map = new HashMap<>(3);
        map.put("otherShippingId", shippingKAHeadDto.getShippingOrderId());
        osh.setOmsExt(JsonUtils.obj2Json(map));

        osh.setWarehouseId("");
        osh.setWarehouseName("");
        osh.setCarType("");
        osh.setWarehouseData("");
        osh.setTmsId(0L);
        osh.setTransUid(0L);
        osh.setWaybillNo("");
        osh.setReceiptStatus(0);
        osh.setDelayType(0);
        osh.setOrderFrom(5);
        osh.setTurnoverboxNum(0);
        osh.setBoxNum(0);
        osh.setIsPrecedence(1);
        osh.setIsValid(1);
        osh.setSeq(1);
        osh.setStatus(1);
        int time = DateUtil.getCurrentTime();
        osh.setCreatedAt(time);
        osh.setUpdatedAt(time);
        osh.setArrivedAt(time);

        //TODO:head_info
        CalShippingHeadVo head = calVo.getHead();
        String ext = head.getExt();
        JSONObject extObject = JSONObject.parseObject(ext);
        osh.setExt(extObject.toJSONString());

        osh.setTmsOrderId(IdGenerator.genId());
        osh.setShippingOrderId(IdGenerator.genId());
        return osh;
    }

    /**
     * 常温品签收  2018-06-25
     *
     * @param orderHead
     * @param orderShippingHead
     * @param head
     * @return
     */

    public static OrderSignHead createSignHead(OrderHead orderHead, OrderShippingHead orderShippingHead, CalOrderReceiptHead head, List<BillPaymentInfo> billPaymentInfoList) {

        OrderSignHead dto = new OrderSignHead();
        dto.setReceiptOrderId(IdGenerator.genId());
        int time = (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
        //来自发货单
        dto.setShippingOrderId(orderShippingHead.getShippingOrderId());
        dto.setWarehouseId(orderShippingHead.getWarehouseId());
        dto.setWarehouseName(orderShippingHead.getWarehouseName());
        dto.setOrderFrom(orderShippingHead.getOrderFrom());
        //来自订单信息
        //在线支付特殊处理
        PayType payType = PayType.indexOf(orderHead.getPayType());
        if (PayType.ONLINE_PAYMENT.equals(payType)) {
            dto.setPayStatus(PayStatus.PAID.getValue());
            dto.setStatus(SignStatus.ARRIVAL.getIndex());
            dto.setPayType(orderHead.getPayChannel());
            // 在线付款，到账时间即为订单到账时间
            dto.setConfirmAt(orderHead.getPayTime());
        } else if (PayType.OPEN_ACCOUNT.equals(payType)) {
            dto.setPayStatus(PayStatus.PAID.getValue());
            dto.setStatus(SignStatus.PAY.getIndex());
            dto.setPayType(orderHead.getPayChannel());
        } else if (PayType.PRE_PAYMENT.equals(payType)) {
            dto.setPayStatus(PayStatus.PAID.getValue());
            dto.setStatus(SignStatus.ARRIVAL.getIndex());
            dto.setConfirmAt(time);
            dto.setPayType(orderHead.getPayChannel());
        } else {
            dto.setPayStatus(PayStatus.NOT_PAID.getValue());
            dto.setStatus(SignStatus.NOT_ARRIVAL.getIndex());
        }
        //订单优惠金额
        dto.setOrderId(orderHead.getOrderCode());
        dto.setAddressId(orderHead.getAddressCode());
        dto.setProvince(orderHead.getProvince() + "");
        dto.setCity(orderHead.getCity() + "");
        dto.setCounty(orderHead.getDistrict() + "");
        dto.setArea(orderHead.getArea() + "");

        dto.setActivedAt(time);
        dto.setCreatedAt(time);
        dto.setUpdatedAt(time);
        dto.setReceiptAt(time);
        dto.setZoneId(orderHead.getRegionCode());
        dto.setUid(orderHead.getUserCode());
        dto.setStorageTypeId(orderHead.getStorageType());
        dto.setPayType(orderHead.getPayChannel());
        dto.setRouteId(orderShippingHead.getRouteId());
        dto.setVenderId(orderHead.getVenderId());

        // 来自计算服务
        dto.setFloorMoney(BigDecimal.ZERO);
        dto.setMoney(BigDecimal.ZERO.compareTo(head.getMoney()) == 0 ? new BigDecimal(0.01) : head.getMoney());
        dto.setCouponMoney(head.getCouponMoney());

        JSONObject extObject = head.getExt();
        JSONObject headInfo = extObject.getJSONObject("head_info");
        headInfo.put("floor_money", BigDecimal.ZERO);
        headInfo.put("money", head.getMoney());
        extObject.put("head_info", headInfo);
        extObject.put("supplier_group_id", orderHead.getSupplierGroupId());
        JSONObject address = orderHead.addressProperties();
        String dMallOrderType = address.getString("dMallOrderType");
        if (StringUtils.isBlank(dMallOrderType)) {
            dMallOrderType = "0";
        }

        extObject.put("dMallOrderType", dMallOrderType);

        if (Optional.ofNullable(billPaymentInfoList).isPresent()) {
            List<String> paySequenceList = billPaymentInfoList.stream().filter(billInfo -> PayStatus.PAID.getValue().equals(billInfo.getPayStatus())).map(BillPaymentInfo::getPaySequence).collect(Collectors.toList());
            extObject.put("pay_payment_no", JSON.toJSONString(paySequenceList));
        }
        dto.setExt(extObject.toJSONString());

        // 预设默认值
        dto.setIsValid(Valid.ENABLE.getValue());
        dto.setTmsId(0L);

        return dto;
    }


    /**
     * @param orderCode
     * @param orderHead
     * @param orderShippingHead
     * @param receiptTime
     * @return
     */
    public static OrderSignHead createSignHead(Long orderCode, OrderHead orderHead, OrderShippingHead orderShippingHead, Integer receiptTime) {

        return createSignHead(orderCode, orderHead, orderShippingHead, null, receiptTime);
    }

    /**
     * 冻品及KA签收
     *
     * @param orderCode
     * @param orderHead
     * @param orderShippingHead
     * @param head
     * @param receiptTime
     * @return
     */
    public static OrderSignHead createSignHead(Long orderCode, OrderHead orderHead, OrderShippingHead orderShippingHead, CalOrderReceiptHead head, Integer receiptTime) {
        OrderSignHead dto = new OrderSignHead();
        dto.setShippingOrderId(orderShippingHead.getShippingOrderId());

        boolean kaFlag = (getUserType(orderHead) == UserType.KA.getIndex());
        //抹零
        if (head == null) {

            if (kaFlag) {
                dto.setFloorMoney(BigDecimal.ZERO);
                dto.setMoney(orderShippingHead.getMoney());
            } else {
                dto.setFloorMoney(BigDecimal.ZERO);
                dto.setMoney(orderShippingHead.getMoney());
            }
        } else {
            //TODO 抹零处理
            if (kaFlag) {
                dto.setFloorMoney(BigDecimal.ZERO);
                dto.setMoney(head.getMoney());
            } else {
                dto.setFloorMoney(BigDecimal.ZERO);
                dto.setMoney(head.getMoney());
            }
        }

        BigDecimal money = dto.getMoney();
        if(money.compareTo(BigDecimal.ZERO) == 0){
            dto.setMoney(new BigDecimal("0.01"));
        }

        dto.setOrderId(orderCode);
        dto.setAddressId(orderHead.getAddressCode());
        dto.setProvince(orderHead.getProvince() + "");
        dto.setCity(orderHead.getCity() + "");
        dto.setCounty(orderHead.getDistrict() + "");
        dto.setArea(orderHead.getArea() + "");
        dto.setCouponMoney(orderHead.getOrderDiscountAmout());
        dto.setZoneId(orderHead.getRegionCode());
        dto.setStorageTypeId(orderHead.getStorageType());
        dto.setUid(orderHead.getUserCode());
        int time = (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
        dto.setActivedAt(time);
        dto.setCreatedAt(time);
        dto.setUpdatedAt(time);
        dto.setTmsId(0L);
        dto.setOrderFrom(1);

        dto.setVenderId(orderHead.getVenderId());

        if (receiptTime == null) {
            dto.setReceiptAt((int) (System.currentTimeMillis() / 1000));
        } else {
            dto.setReceiptAt(receiptTime);
        }

        int orderPaytype = orderHead.getPayType();

        if (orderPaytype == PayType.ONLINE_PAYMENT.getValue()) {
            dto.setPayStatus(PayStatus.PAID.getValue());
            dto.setStatus(SignStatus.PAY.getIndex());
            dto.setPayType(PayChannel.PRE_PAYMENT.getIndex());
        } else if (orderPaytype == PayType.PAY_ON_DELIVERY.getValue()) {
            if (kaFlag) {
                dto.setPayStatus(PayStatus.PAID.getValue());
                dto.setStatus(SignStatus.PAY.getIndex());
                dto.setPayType(PayChannel.ON_CREDIT.getIndex());
            } else {
                dto.setPayStatus(PayStatus.NOT_PAID.getValue());
                dto.setStatus(SignStatus.NOT_ARRIVAL.getIndex());
                dto.setPayType(PayChannel.NO.getIndex());
            }
        } else if (orderPaytype == PayType.OPEN_ACCOUNT.getValue()) {
            dto.setPayStatus(PayStatus.PAID.getValue());
            dto.setStatus(SignStatus.PAY.getIndex());
            dto.setPayType(PayChannel.ON_CREDIT.getIndex());
        } else if (orderPaytype == PayType.PRE_PAYMENT.getValue()) {
            dto.setPayStatus(PayStatus.PAID.getValue());
            dto.setStatus(SignStatus.PAY.getIndex());
            dto.setPayType(PayChannel.PRE_PAYMENT.getIndex());
        } else {
            dto.setPayStatus(PayStatus.NOT_PAID.getValue());
            dto.setStatus(SignStatus.NOT_ARRIVAL.getIndex());
            dto.setPayType(PayChannel.NO.getIndex());
        }

        dto.setIsValid(Valid.ENABLE.getValue());
        dto.setWarehouseId(orderShippingHead.getWarehouseId());
        dto.setWarehouseName(orderShippingHead.getWarehouseName());

        return dto;
    }

    public static List<OrderSignDetail> receiptDetails(List<CalOrderReceiptDetail> detailList, OrderHead orderHead, Long receiptOrderId, Map<Integer,OrderShippingDetail> detailMap, OrderSignHead oshHead, String logSign) {
        List<OrderSignDetail> signDetails = new ArrayList<>();
        int time = (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
        try {

            BigDecimal totalQty = BigDecimal.ZERO;
            BigDecimal totalRealQty = BigDecimal.ZERO;
            for (CalOrderReceiptDetail detail : detailList) {
                if (detail == null) {
                    log.info(logSign + "订单号" + orderHead.getOrderCode() + ",签收计算服务解析明细为空。");
                    throw new BusinessException(ReturnCode.REQUEST_FAIL, "此订单未生成发货单.请查询");
                }
                OrderShippingDetail shippingDetail = detailMap.get(detail.getItemCode());
                if(null == shippingDetail){
                    throw new BusinessException(ReturnCode.REQUEST_FAIL, "行项目有误 " + detail.getItemCode());
                }
                OrderSignDetail signDetail = new OrderSignDetail();
                JSONObject ext = detail.getExt();
                signDetail.setReceiptOrderId(receiptOrderId);
                signDetail.setPackageId(ext.getInteger("package_id"));
                signDetail.setExt(ext.toJSONString());
                signDetail.setSkuId(detail.getSkuId());
                signDetail.setSkuName(detail.getSkuName());

                signDetail.setItemId(shippingDetail.getItemId());
                signDetail.setSaleUnit(detail.getSaleUnit());
                signDetail.setQty(detail.getQty());
                signDetail.setRealQty(detail.getRealQty());
                signDetail.setStatus(1);
                signDetail.setCreatedAt(time);
                signDetail.setUpdatedAt(time);
                signDetail.setZoneId(orderHead.getRegionCode());
                signDetail.setVenderId(orderHead.getVenderId());
                signDetail.setItemCode(detail.getItemCode());
                signDetail.setSupplierOrg(shippingDetail.getSupplierOrg());
                signDetail.setPrice(detail.getPrice());
                signDetail.setMoney(detail.getMoney());
                signDetail.setTmsId(0L);

                totalQty = totalQty.add(detail.getQty());
                totalRealQty = totalRealQty.add(detail.getRealQty());

                signDetails.add(signDetail);
            }
            oshHead.setSkuCount(totalQty);
            oshHead.setRealSkuCount(totalRealQty);

        } catch (Exception e) {
            log.error(logSign + "订单号" + orderHead.getOrderCode() + ",签收计算服务解析明细失败。");
            log.error(e.getMessage(), e);
            throw new BusinessException(ReturnCode.REQUEST_FAIL, "签收计算服务解析明细失败");
        }

        return signDetails;
    }

    public static int getUserType(OrderHead orderHead) {
        //用户类型：1-普通用户  2-企业用户 3-KA用户
        if (orderHead != null && StringUtils.isNotBlank(orderHead.getAddressInfo())) {
            String addressInfo = orderHead.getAddressInfo();
            JSONObject addressInfoJson = JSON.parseObject(addressInfo);
            String userType = addressInfoJson.getString("user_type");
            if (StringUtils.isNotBlank(userType)) {
                return Integer.parseInt(userType);
            }
        } else {
            throw new BusinessException(ReturnCode.REQUEST_FAIL, "订单信息不存在");
        }

        return UserType.PERSONAL.getIndex();
    }

    /**
     * @param orderHead
     * @return
     */
    public static String getMarketName(OrderHead orderHead) {
        if (orderHead != null && StringUtils.isNotBlank(orderHead.getAddressInfo())) {
            String addressInfo = orderHead.getAddressInfo();
            JSONObject addressInfoJson = JSON.parseObject(addressInfo);
            String marketName = addressInfoJson.getString("market_name");
            if (StringUtils.isNotBlank(marketName)) {
                return marketName;
            }
        }

        return "";
    }

    /**
     * @param orderHead
     * @return
     */
    public static String getProviderId(OrderHead orderHead) {
        if (orderHead != null && StringUtils.isNotBlank(orderHead.getExt())) {
            JSONObject extJson = JSON.parseObject(orderHead.getExt());
            String providerId = extJson.getString("providerId");

            if (StringUtils.isNotBlank(providerId)) {
                return providerId;
            }
        }

        return "";
    }

//    public static void main(String args[]) {
//        List<BillPaymentInfo> billPaymentInfoList = null;
//
//        List<String> paySequenceList = billPaymentInfoList.stream().filter(billInfo -> PayStatus.PAID.getValue().equals(billInfo.getPayStatus())).map(BillPaymentInfo::getPaySequence).collect(Collectors.toList());
//        System.out.print(paySequenceList);
//
//    }
}
